package Leetcode;

import java.util.Arrays;

public class 力扣912_快排 {
    public static void main(String[] args) {
        int[] nums = {3, 2, 1, 5, 6, 4};
        quickSortDesc(nums);
        System.out.println(Arrays.toString(nums));
    }

    public static void quickSortAsc(int[] nums) {
        quickSortAsc(nums, 0, nums.length - 1);
    }

    public static void quickSortDesc(int[] nums) {
        quickSortDesc(nums, 0, nums.length - 1);
    }

    /**
     * less 小于基准的数放到less下标之前
     * more 大于基准的数放到more下标之后
     * 数组最后一个数作为 基准数
     * arr[r] 基准数 arr[less] 当前数
     * 拿着当前数据和基准数比较
     * 小于等于：小于区域加1
     * 大于：把当前数和大于区域的前一位交换 当前位置下标不变 大于区域减1
     */
    private static void quickSortAsc(int[] nums, int l, int r) {
        if (l < r) {
            int less = l;
            int more = r - 1;
            while (less <= more) {
                if (nums[less] > nums[r]) {
                    swap(nums, less, more);
                    more--;
                } else {
                    less++;
                }
            }
            swap(nums, more + 1, r);
            quickSortAsc(nums, l, more);
            quickSortAsc(nums, more + 1, r);
        }
    }

    /**
     * 同正序 只是改变下大小判断
     */
    private static void quickSortDesc(int[] nums, int l, int r) {
        if (l < r) {
            int less = l;
            int more = r - 1;
            while (less <= more) {
                if (nums[less] < nums[r]) {
                    swap(nums, less, more);
                    more--;
                } else {
                    less++;
                }
            }
            swap(nums, more + 1, r);
            quickSortDesc(nums, l, more);
            quickSortDesc(nums, more + 1, r);
        }
    }

    /**
     * 同quickSortDesc 只是从选择基准值是第一个
     */
    private static void quickSortDesc2(int[] nums, int l, int r) {
        if (l < r) {
            int less = l + 1;
            int more = r;
            while (less <= more) {
                if (nums[more] > nums[l]) {
                    swap(nums, less, more);
                    less++;
                } else {
                    more--;
                }
            }
            swap(nums, l, less - 1);
            quickSortDesc2(nums, l, less - 1);
            quickSortDesc2(nums, less, r);
        }
    }

    private static void swap(int[] nums, int l, int r) {
        int num = nums[l];
        nums[l] = nums[r];
        nums[r] = num;
    }
}
